const { exec } = require('../db/mysql');

// 获取博客列表
const getList = async (author = '', keyword = '') => {

    let sql = `select * from blogs where 1=1`;
    if (author) {
        sql += ` and author like '%${author}%'`;
    }
    if (keyword) {
        sql += ` and title like '%${keyword}%' or content like '%${keyword}%'`;
    }
    sql += ` order by createtime desc`;
    const res = await exec(sql);
    return res;
}

// 获取博客详情
const getDetail = async (id) => {
    let sql = `select * from blogs where id=${id}`;
    const res = await exec(sql);
    return res[0];
}

// 新增一篇博客
const add = async (blogData = {}) => {
    const { title, content, author } = blogData;
    const createTime = Date.now();
    const sql = `insert into blogs (title, content, author, createtime) values ('${title}', '${content}', '${author}', ${createTime})`;
    const res = await exec(sql);
    return {
        id: res.insertId,
        ...blogData
    }
}

// 更新博客内容
const updateBlog = async (id, blogData = {}) => {
    const { title, content } = blogData;
    let sql = `update blogs set`;
    const updateFields = [];
    
    if (title) {
        updateFields.push(`title='${title}'`);
    }
    if (content) {
        updateFields.push(`content='${content}'`);
    }
    
    sql += ' ' + updateFields.join(', ');
    sql += ` where id=${id}`;
    
    const res = await exec(sql);
    if (res.affectedRows > 0) {
        return true;
    }
    return false;
}


const delBlog = async (id) => {
    let sql = `delete from blogs where id=${id}`;
    const res = await exec(sql);
    if (res.affectedRows > 0) {
        return true;
    }
    return false;
}



module.exports = {
    getList, getDetail, add, updateBlog,delBlog
}